import React, {Component} from 'react'
import './index.css'

const MyContext = React.createContext()
const {Provider, Consumer} = MyContext

export default class Context extends Component {

    state = {
        userName: 'jerry',
        age: 18
    }
    render() {
        const {userName, age} = this.state
        return (
            <div className='aContainer'>
                <h3>A组件</h3>
                <h4>用户名：{userName}</h4>
                <Provider value={{userName, age}}>
                    <B />
                </Provider>
            </div>
        )
    }
}

class B extends Component {
    static contextType = MyContext
    render() {
        return (
            <div className='bContainer'>
                <h3>B组件</h3>
                <h4>从A组件接收到数据：
                    <Consumer>
                        {
                            value => {
                                return `${value.userName}---${value.age}`
                            }
                        }
                    </Consumer>
                </h4>
                <C />
            </div>
        )
    }
}

class C extends Component {
    static contextType = MyContext
    render() {
        return (
            <div className='cContainer'>
                <h3>C组件</h3>
                <h4>从A组件接收到数据：{this.context.userName}---{this.context.age}</h4>
            </div>
        )
    }
}